
<template>
    <a-card :bordered="false">
        <div style="margin: 20px;">
            <a-table :columns="columns" :dataSource="dataSource" :pagination="ipagination"
                :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
                <!-- 操作 -->
                <div slot="creator" slot-scope="text,record">
                    <span v-for="(item, index) in  record.creator " :key="index">{{ item.crer }}</span>
                </div>

                <span slot="action" slot-scope="text,record">
                    <!-- 修改 -->
                    <a v-if="record.action.includes('edit')" class="action-btn" @click="addIndex(record)">添加指标</a>
                    <!-- 删除 -->
                    <a-popconfirm style="margin: 0 20px;" ok-text="确定" cancel-text="取消" @confirm="confirm(record)"
                        @cancel="cancel" v-if="record.action.includes('del')">
                        <template slot="title">
                            <p>你确定要删除这条数据吗?</p>
                        </template>
                        <a class="action-btn">删除</a>
                    </a-popconfirm>
                </span>
                <div slot="zhibiao" slot-scope="text,record">
                    {{ record }}
                </div>
            </a-table>
            <div class="btnStyle">
                <a-form-item :wrapperCol="{ span: 24, offset: 5 }">
                    <a-button class="btnLast" type="primary" @click="lastStep">上一步</a-button>
                </a-form-item>
            </div>
        </div>


        <!-- 指标弹框 -->
        <div class="chouti">
            <a-drawer title="企业指标" placement="right" :closable="false" :visible="visible"
                :after-visible-change="afterVisibleChange" @close="onClose" width="800">
                <div>企业指标</div>
                <a-tree v-model="checkedKeysT" checkable :tree-data="treeDataT" @expand="onExpandT" @select="onSelectT"
                    @check="handleCheck">
                </a-tree>
                <a-button class="choutibtn" @click="handleButton" style="margin: ;">确定</a-button>
            </a-drawer>
        </div>
    </a-card>
</template>
<script>

import axios from 'axios'

export default {

    data() {
        return {
            visible: false,
            expandedKeys: ['0-0-0'],
            autoExpandParent: true,
            checkedKeys: [],
            bigcheckedKeys: [],
            selectedKeys: [],
            treeData: [],
            treeDatas: [],
            newarr: [],
            index: 0,
            treeDataT: [],
            checkedKeysT: [],
            selectedKeysT: [],
            addlist: [],
            bddlist: [],
            lskey: '',
            filteritem: [],
            columns: [],
            dataSource: [],
            selectedRowKeys: [],
            // 分页器
            ipagination: {
                current: 1,
                pageSize: 20,
                pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + '-' + range[1] + ' 共' + total + '条'
                },
                showQuickJumper: true,
                showSizeChanger: true,
                total: 0
            },
            // 人员
            personnel: '',
            // 部门
            section: '',
            checkedKeysT: [],
            treeDataT: [],
            bddlist: [],
            selectedKeysT: [],

            therec: {},
            pagesIndex: '',
            dataSources: [],
            resInfo: {}
        }
    },

    mounted() {
        //新的
        this.pointerRequestFirm()

        let res = JSON.parse(localStorage.getItem('tableData'))
        this.$bus.$on('filtertable', a => {
            if (a) {
                this.bbb()
                this.dataSource = res.data
            }
        })

        this.$bus.$on('nextTitle', (a) => {

            this.filteritem = [...a.small, ...a.big]
        })
        this.templateColumns()
        this.PointerRequestIndex()

        this.aaa()


        //-------原来的


        // let ress = JSON.parse(localStorage.getItem('formInfoValue'))
        // this.resInfo = ress
        // console.log(this.resInfo, '部门架构传递JSON.parse////////')

    },
    watch: {
        checkedKeys(val) {
            // console.log('onCheck', val);
        },
    },

    methods: {
        aaa() {

            let res = JSON.parse(localStorage.getItem('formInfoValue'))
            console.log(res, '////')
            this.$bus.$emit('formInfo', res)
        },
        bbb() {
            let res = JSON.parse(localStorage.getItem('addkey'))
            console.log(res, '////')
            this.$bus.$emit('formInfo', res)
        },
        //  添加指标
        addIndex(rec) {
            this.visible = true

            this.therec = rec
            this.PointerRequestIndex()
        },

        async PointerRequestIndex() {
            const result = await axios.get('/mock/tableTemplateIndex')
            this.treeDataT = result.data.data
        },
        afterVisibleChange(val) {
            console.log('visible', val);
        },

        onClose() {
            this.visible = false;
        },
        onExpandT(expandedKeys) {
            this.bddlist = expandedKeys
        },
        onSelectT(selectedKeys, info) {

            this.selectedKeysT = selectedKeys;
            // console.log(this.selectedKeysT, '/////////')
        },

        // 点击确定按钮
        handleButton() {
            this.visible = false
            let list = [...this.addlist, ...this.bddlist]
            //list 里面是 勾选的数据 和  tree结构 展开的数据
            this.removeNodes(this.treeDataT, list)
            // console.log(this.treeDataT,'////////aaaaaaaaaaaaaaaa')
            this.handletwotree(this.treeDataT)
            this.checkedKeysT = []
        },

        async pointerRequestFirm() {
            const result = await axios.get('/mock/tebleTemplateTree')
            this.treeDatas = result.data.data
            this.removeNodes(this.treeDatas, this.filteritem)
            this.handleTreeDatas(this.treeDatas)

        },

        handleTreeDatas(tree) {
            let arr = []
            tree.forEach(item => {
                item.children.forEach((items, indexs) => {

                    items.children.forEach((val, index) => {

                        val.bumen = items.title
                        arr.push({ val })

                        this.dataSource.push({
                            "serialNumber": arr.length,//这个是序号
                            "name": val.title,
                            "timer": val.bumen,
                            "action": ["edit", "del"],

                        })
                    });
                })
            });
        },
        handletwotree(tree) {
            let trearr = []
            // "creator":this.treeDataT?this.treeDataT:''
            this.dataSource.forEach((item) => {
                if (item == this.therec) {
                    tree[0].children.forEach((items) => {
                        items.children.forEach((val) => {
                            trearr.push({ crer: val.title })

                        })
                    })
                }
            })
            console.log(trearr)
            this.therec.creator = trearr
            console.log(this.therec)
        },

        //这个方法是过滤没选的 只留下选中的  第一个参数就是 treedata 第二个参数 是 选中的key数组
        removeNodes(tree, keysToRemove) {
            for (let i = tree.length - 1; i >= 0; i--) {
                const node = tree[i];
                // console.log(node)
                if (keysToRemove.includes(node.key)) {
                    if (node.children && node.children.length > 0) {
                        this.removeNodes(node.children, keysToRemove);
                    }
                } else {
                    tree.splice(i, 1);
                }
            }
            // console.log(this.treeData)
        },

        async PointerRequestIndex() {
            const result = await axios.get('/mock/tableTemplateIndex')
            // let lots =  { "title":"custiom"} //重要方法的 重要的步骤
            // this.addSlotToLastChildren(result.data.data,lots)
            this.treeDataT = result.data.data


        },

        // 点击确定按钮
        handleButtonIs() {
            this.index = 0
            let list = [...this.addlist, ...this.bddlist]
            //list 里面是 勾选的数据 和  tree结构 展开的数据
            this.removeNodes(this.treeDataT, list)
            // this.addToChildrenByKey(this.treeData, this.lskey, this.treeDataT)
            //然后调用了两个方法 一个排除没选中的 一个是 加children de

        },
        handleCheck(checkedKeys, { checked: bool, checkedNodes, node, event }) {
            this.addlist = checkedKeys
        },

        //很重要******
        //       addSlotToLastChildren(data, obj) {
        //   data.forEach(node => {
        //     if (Array.isArray(node.children) && node.children.length > 0) {
        //       this.addSlotToLastChildren(node.children, obj);
        //     } else {
        //       if (!node.scopedSlots) {
        //         node.scopedSlots = {};
        //       }
        //       node.scopedSlots = Object.assign(node.scopedSlots, obj);
        //     }
        //   });
        // },

        // 示例数据
        // 获取表头数据
        templateColumns() {
            this.$nextTick(async () => {
                const result = await axios.get('/mock/tableTemplateAdd')
                this.columns = result.data.data
                // console.log(result, '模拟表头数据------------')
            })
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },


        add(item) {
            // console.log(item, '////')
            this.index = 1 //这个控制 显示的 
            this.PointerRequestIndex()
            this.lskey = item.key //这是获取的张强 key

        },

        // 三个参数 第一个是 treedata 第二个是 店家添加 获取的 key 比如张强 的添加 拿到的就是 张强的 key 然后 第三个 就是 指标
        //里面的 选中的 数据 这个方法就是 添加的 把指标放到张强的children离
        addToChildrenByKey(tree, key, newChild) {
            if (!Array.isArray(tree)) {
                return;
            }

            for (let i = 0; i < tree.length; i++) {
                const node = tree[i];

                if (node.key === key) {
                    if (!node.children) {
                        node.children = [];
                    }
                    node.children = node.children.concat(newChild); // 使用 concat 方法合并子项这里的这个方法 不会触发界面重新渲染
                    //如果用 push  是可以的 但是 push 数据结构新加的 不行 多一层数组 渲染不出来tree
                    return;
                }

                if (Array.isArray(node.children)) {
                    this.addToChildrenByKey(node.children, key, newChild);
                }
            }
        },

        onExpand(expandedKeys) {
            // console.log('onExpand', expandedKeys);
            // if not set autoExpandParent to false, if children expanded, parent can not collapse.
            // or, you can remove all expanded children keys.
            this.expandedKeys = expandedKeys;
            this.autoExpandParent = false;
        },
        onExpandT(expandedKeys) {
            // console.log('onExpand', expandedKeys);
            // if not set autoExpandParent to false, if children expanded, parent can not collapse.
            // or, you can remove all expanded children keys.
            // this.expandedKeysT = expandedKeys;
            this.bddlist = expandedKeys
        },
        onCheck(checkedKeys) {
            // console.log('onCheck', checkedKeys);
            this.checkedKeys = checkedKeys;
        },
        onSelect(selectedKeys, info) {
            // console.log('onSelect', info);
            this.selectedKeys = selectedKeys;
        },
        onSelectT(selectedKeys, info) {

            this.selectedKeysT = selectedKeys;
            // console.log(this.selectedKeysT, '/////////')
        },

        // 删除成功
        confirm(record) {

            this.dataSource = this.dataSource.filter((item) => {
                return item.name !== record.name

            })
            // console.log(res,'//aaaaaa')
            this.dataSource.forEach((item, index) => {
                item.serialNumber = index + 1
            })
            this.$message.success('删除成功')

        },

        // 取消删除
        cancel() {
            this.$message.error('取消删除')
        },

        // 上一步
        lastStep() {
            let idx = this.filteritem.length > 0 ? 1 : 0

            this.$bus.$emit('pages', idx)
        },
    },
};
</script>
<style scoped lang="scss">
.tree {
    max-width: 70%;
    height: 560px;
    margin-left: 40%;
    display: flex;
    // flex-direction: column;

    .treeStyle {
        width: 400px;
        background: #fff;
        opacity: .8;
    }

    .diatree {
        width: 400px;
        background: #fff;
    }
}

.btnS {
    background: red;
}

.chouti {
    position: relative;
}

.choutibtn {
    position: absolute;
    bottom: 30px;
    right: 20px;
}

.btnStyle {
    margin: 5% 40%;
    .btnLast {
        // margin: 10% 30% 0;
    }
}
</style>
  